package com.cinema.servlet.user;

import com.cinema.dao.UserDAO;
import com.cinema.entity.User;
import com.cinema.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 用户注册Servlet
 */
public class RegisterServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();
    
    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    // 邮箱正则表达式
    private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$";
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 显示注册页面
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String realName = request.getParameter("realName");
        String gender = request.getParameter("gender");
        
        // 参数验证
        String validationError = validateInput(username, password, confirmPassword, phone, email);
        if (validationError != null) {
            request.setAttribute("error", validationError);
            setFormData(request, username, phone, email, realName, gender);
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }
        
        try {
            // 检查用户名是否已存在
            User existUser = userDAO.findByUsername(username);
            if (existUser != null) {
                request.setAttribute("error", "用户名已存在，请选择其他用户名");
                setFormData(request, username, phone, email, realName, gender);
                request.getRequestDispatcher("/register.jsp").forward(request, response);
                return;
            }
            
            // 检查手机号是否已存在
            User existPhoneUser = userDAO.findByPhone(phone);
            if (existPhoneUser != null) {
                request.setAttribute("error", "手机号已被注册，请使用其他手机号");
                setFormData(request, username, phone, email, realName, gender);
                request.getRequestDispatcher("/register.jsp").forward(request, response);
                return;
            }
            
            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setPassword(PasswordUtil.encrypt(password));
            user.setPhone(phone);
            user.setEmail(email);
            user.setRealName(realName);
            user.setGender(gender);
            
            // 注册用户
            boolean success = userDAO.register(user);
            
            if (success) {
                request.setAttribute("success", "注册成功！请登录");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                request.setAttribute("error", "注册失败，请稍后重试");
                setFormData(request, username, phone, email, realName, gender);
                request.getRequestDispatcher("/register.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "注册过程中发生错误，请稍后重试");
            setFormData(request, username, phone, email, realName, gender);
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }
    
    /**
     * 验证输入参数
     */
    private String validateInput(String username, String password, String confirmPassword, 
                               String phone, String email) {
        
        if (isEmpty(username) || isEmpty(password) || isEmpty(phone)) {
            return "用户名、密码和手机号为必填项";
        }
        
        if (username.length() < 3 || username.length() > 20) {
            return "用户名长度必须在3-20个字符之间";
        }
        
        if (password.length() < 6 || password.length() > 20) {
            return "密码长度必须在6-20个字符之间";
        }
        
        if (!password.equals(confirmPassword)) {
            return "两次输入的密码不一致";
        }
        
        if (!Pattern.matches(PHONE_REGEX, phone)) {
            return "请输入有效的手机号码";
        }
        
        if (!isEmpty(email) && !Pattern.matches(EMAIL_REGEX, email)) {
            return "请输入有效的邮箱地址";
        }
        
        return null;
    }
    
    /**
     * 设置表单数据（用于回显）
     */
    private void setFormData(HttpServletRequest request, String username, String phone, 
                           String email, String realName, String gender) {
        request.setAttribute("username", username);
        request.setAttribute("phone", phone);
        request.setAttribute("email", email);
        request.setAttribute("realName", realName);
        request.setAttribute("gender", gender);
    }
    
    /**
     * 检查字符串是否为空
     */
    private boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}
